package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.util.SMSUtils;
import com.itheima.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/sendMsg")
    public R sendMessage(@RequestBody User user, HttpServletRequest request) {
//        int i = RandomUtils.nextInt(0, 100000);
//        String code=String.valueOf(i);
        Integer integer = ValidateCodeUtils.generateValidateCode(6);
        String code = String.valueOf(integer);
        String phone = user.getPhone();
//        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
//        wrapper.eq(User::getPhone,phone);
//        User user1 = userService.getOne(wrapper);
//        Long id = user1.getId();
//        request.getSession().setAttribute("userId",id);

//        SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", phone, code);
        request.getSession().setAttribute("code", code);
//        redisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);
        log.info(code);


        return R.success("验证码发送成功！");


    }

    @PostMapping("/login")
    public R login(@RequestBody Map map, HttpServletRequest request) {
        String phone = (String) map.get("phone");
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        User user1 = userService.getOne(wrapper);

        if (user1 == null) {
            User u = new User();
            u.setStatus(1);
            u.setPhone(phone);
            userService.save(u);
        }

        User one = userService.getOne(wrapper);


        String code1 = (String) request.getSession().getAttribute("code");
        if (code1.equals((String) map.get("code"))) {
            request.getSession().setAttribute("userId", one.getId());

            return R.success("登录成功！");
        }
        return R.error("验证码输入错误");
    }

    @PostMapping("/loginout")
    public R logout(HttpSession session) {
        session.invalidate();

        return R.success("退出成功！");

    }
}
